package zzzhc.image.ui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;

import zzzhc.image.core.ImageCapture;
import zzzhc.image.core.ImageCaptureListener;
import zzzhc.image.model.AppModel;
import zzzhc.image.model.CapturePanelModel;
import zzzhc.image.model.CaptureTableModel;
import javax.swing.ListSelectionModel;

public class CapturePanel extends JPanel implements ImageCaptureListener {

	private static final long serialVersionUID = 1L;

	private JLabel jLabel = null;

	private JTextField sourceUrlText = null;

	private JLabel jLabel1 = null;

	private JTextField regexText = null;

	private JLabel jLabel2 = null;

	private JTextField imageUrlText = null;

	private JLabel jLabel3 = null;

	private JScrollPane jScrollPane = null;

	private JTable jTable = null;

	private JSpinner countSpinner = null;

	private JButton captureButton = null;

	private CapturePanelModel capturePanelModel = AppModel.getInstance()
			.getCapturePanelModel(); // @jve:decl-index=0:

	private CaptureTableModel captureTableModel = capturePanelModel
			.getCaptureTableModel();

	private ImageCapture imageCapture;

	private JPanel jPanel = null;

	private JButton cancelButton = null;

	private JButton jButton = null;

	private JButton jButton1 = null;

	private JLabel jLabel4 = null;

	private JTextField cookieText = null;

	private JButton jButton2 = null;

	public CapturePanelModel getCapturePanelModel() {
		capturePanelModel.setSourceUrl(sourceUrlText.getText());
		capturePanelModel.setRegex(regexText.getText());
		capturePanelModel.setImageUrl(imageUrlText.getText());
		capturePanelModel.setCount((Integer) countSpinner.getValue());
		capturePanelModel.setCookie(cookieText.getText());
		return capturePanelModel;
	}

	/**
	 * This is the default constructor
	 */
	public CapturePanel() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		GridBagConstraints gridBagConstraints22 = new GridBagConstraints();
		gridBagConstraints22.fill = GridBagConstraints.BOTH;
		gridBagConstraints22.gridy = 2;
		gridBagConstraints22.weightx = 1.0;
		gridBagConstraints22.gridx = 1;
		GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
		gridBagConstraints12.gridx = 0;
		gridBagConstraints12.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints12.gridy = 2;
		jLabel4 = new JLabel();
		jLabel4.setText("Cookie注入:");
		GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
		gridBagConstraints21.gridy = 6;
		gridBagConstraints21.gridwidth = 2;
		gridBagConstraints21.gridx = 0;
		GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
		gridBagConstraints11.gridy = 4;
		gridBagConstraints11.gridwidth = 2;
		gridBagConstraints11.gridx = 0;
		GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
		gridBagConstraints7.gridx = 1;
		gridBagConstraints7.anchor = GridBagConstraints.WEST;
		gridBagConstraints7.fill = GridBagConstraints.NONE;
		gridBagConstraints7.gridy = 4;
		GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
		gridBagConstraints8.fill = GridBagConstraints.BOTH;
		gridBagConstraints8.gridy = 7;
		gridBagConstraints8.weightx = 1.0;
		gridBagConstraints8.weighty = 1.0;
		gridBagConstraints8.gridwidth = 2;
		gridBagConstraints8.gridx = 0;
		GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
		gridBagConstraints6.gridx = 0;
		gridBagConstraints6.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints6.gridy = 4;
		jLabel3 = new JLabel();
		jLabel3.setText("采集数量:");
		GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
		gridBagConstraints5.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints5.gridy = 3;
		gridBagConstraints5.weightx = 1.0;
		gridBagConstraints5.gridx = 1;
		GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
		gridBagConstraints4.gridx = 0;
		gridBagConstraints4.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints4.gridy = 3;
		jLabel2 = new JLabel();
		jLabel2.setText("图片地址:");
		GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
		gridBagConstraints3.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints3.gridy = 1;
		gridBagConstraints3.weightx = 1.0;
		gridBagConstraints3.gridx = 1;
		GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
		gridBagConstraints2.gridx = 0;
		gridBagConstraints2.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints2.gridy = 1;
		jLabel1 = new JLabel();
		jLabel1.setText("地址捕获正则式:");
		GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
		gridBagConstraints1.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints1.gridy = 0;
		gridBagConstraints1.weightx = 1.0;
		gridBagConstraints1.gridx = 1;
		GridBagConstraints gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.gridy = 0;
		jLabel = new JLabel();
		jLabel.setText("图片来源地址:");
		this.setSize(400, 300);
		this.setLayout(new GridBagLayout());
		this.add(jLabel, gridBagConstraints);
		this.add(getSourceUrlText(), gridBagConstraints1);
		this.add(jLabel1, gridBagConstraints2);
		this.add(getRegexText(), gridBagConstraints3);
		this.add(jLabel2, gridBagConstraints4);
		this.add(getImageUrlText(), gridBagConstraints5);
		this.add(jLabel3, gridBagConstraints6);
		this.add(getJScrollPane(), gridBagConstraints8);
		this.add(getCountSpinner(), gridBagConstraints7);
		this.add(getJPanel(), gridBagConstraints21);
		this.add(jLabel4, gridBagConstraints12);
		this.add(getCookieText(), gridBagConstraints22);
	}

	/**
	 * This method initializes sourceUrlText
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getSourceUrlText() {
		if (sourceUrlText == null) {
			sourceUrlText = new JTextField();
			sourceUrlText.setColumns(40);
		}
		return sourceUrlText;
	}

	/**
	 * This method initializes regexText
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getRegexText() {
		if (regexText == null) {
			regexText = new JTextField();
		}
		return regexText;
	}

	/**
	 * This method initializes imageUrlText
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getImageUrlText() {
		if (imageUrlText == null) {
			imageUrlText = new JTextField();
			imageUrlText.setColumns(40);
		}
		return imageUrlText;
	}

	/**
	 * This method initializes jScrollPane
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable
	 * 
	 * @return javax.swing.JTable
	 */
	private JTable getJTable() {
		if (jTable == null) {
			jTable = new JTable();
			jTable.setRowHeight(80);
			jTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			jTable.setShowGrid(true);
			jTable.setModel(captureTableModel);
			jTable.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyTyped(java.awt.event.KeyEvent e) {
					// boolean modifierMatch = (e.getModifiers() &
					// KeyEvent.CTRL_MASK) != 0;
					if (e.getKeyChar() == KeyEvent.VK_DELETE) {
						int[] rowes = jTable.getSelectedRows();
						for (int i = rowes.length - 1; i >= 0; i--) {
							captureTableModel.removeRow(rowes[i]);
						}
						jTable.updateUI();
					}
				}
			});
			jTable.setDefaultRenderer(BufferedImage.class,
					new ImageTableCellRenderer(2));
		}
		return jTable;
	}

	/**
	 * This method initializes countSpinner
	 * 
	 * @return javax.swing.JSpinner
	 */
	private JSpinner getCountSpinner() {
		if (countSpinner == null) {
			SpinnerNumberModel spinnerNumberModel = new SpinnerNumberModel();
			spinnerNumberModel.setMinimum(new Integer(1));
			spinnerNumberModel.setMaximum(new Integer(1000));
			countSpinner = new JSpinner();
			countSpinner.setModel(spinnerNumberModel);
			countSpinner.setValue(new Integer(50));
		}
		return countSpinner;
	}

	/**
	 * This method initializes captureButton
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getCaptureButton() {
		if (captureButton == null) {
			captureButton = new JButton();
			captureButton.setText("开始采集");
			captureButton
					.addActionListener(new java.awt.event.ActionListener() {
						public void actionPerformed(java.awt.event.ActionEvent e) {
							imageCapture = new ImageCapture();
							imageCapture
									.setImageCaptureListener(CapturePanel.this);
							imageCapture.setModel(getCapturePanelModel());
							imageCapture.start();
						}
					});
		}
		return captureButton;
	}

	public void finished() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				captureButton.setEnabled(true);
				cancelButton.setEnabled(false);
			}
		});
	}

	public void start() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				captureButton.setEnabled(false);
				cancelButton.setEnabled(true);
			}
		});
	}

	/**
	 * This method initializes jPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
			gridBagConstraints10.gridx = 4;
			gridBagConstraints10.gridy = 0;
			GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.gridx = 3;
			gridBagConstraints9.gridy = 0;
			jPanel = new JPanel();
			jPanel.setLayout(new GridBagLayout());
			jPanel.add(getCaptureButton(), new GridBagConstraints());
			jPanel.add(getCancelButton(), new GridBagConstraints());
			jPanel.add(getJButton(), new GridBagConstraints());
			jPanel.add(getJButton1(), gridBagConstraints9);
			jPanel.add(getJButton2(), gridBagConstraints10);
		}
		return jPanel;
	}

	/**
	 * This method initializes cancelButton
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getCancelButton() {
		if (cancelButton == null) {
			cancelButton = new JButton();
			cancelButton.setText("停止采集");
			cancelButton.setEnabled(false);
			cancelButton.setActionCommand("取消采集");
			cancelButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if (imageCapture != null) {
						imageCapture.stop();
					}
				}
			});
		}
		return cancelButton;
	}

	/**
	 * This method initializes jButton
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setText("清除");
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					captureTableModel.clearAll();
				}
			});
		}
		return jButton;
	}

	/**
	 * This method initializes jButton1
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("保存");
			jButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					JFileChooser chooser = new JFileChooser();
					chooser.setFileFilter(new FileFilter() {

						@Override
						public boolean accept(File f) {
							return f.isDirectory();
						}

						@Override
						public String getDescription() {
							return "directory";
						}

					});
					chooser.setCurrentDirectory(new File("."));
					chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					int retVal = chooser.showSaveDialog(CapturePanel.this);
					if (retVal == JFileChooser.APPROVE_OPTION) {
						int count = captureTableModel.getRowCount();
						File dir = chooser.getSelectedFile();
						int successCount = 0;
						for (int i = 0; i < count; i++) {
							BufferedImage image = (BufferedImage) captureTableModel
									.getValueAt(i, 1);
							String code = (String) captureTableModel
									.getValueAt(i, 2);
							if (code == null || "".equals(code)) {
								continue;
							}
							try {
								ImageIO.write(image, "jpeg", new File(dir, code
										+ ".jpeg"));
								successCount++;
							} catch (Exception ex) {
								JOptionPane.showConfirmDialog(
										CapturePanel.this, ex.getMessage());
							}
						}
						if (successCount > 0) {
							JOptionPane.showConfirmDialog(CapturePanel.this,
									"总共" + count + "个图片," + "成功保存"
											+ successCount + "个", "提示",
									JOptionPane.YES_OPTION);
						}
					}
				}
			});
		}
		return jButton1;
	}

	/**
	 * This method initializes cookieText
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getCookieText() {
		if (cookieText == null) {
			cookieText = new JTextField();
		}
		return cookieText;
	}

	/**
	 * This method initializes jButton2
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			jButton2.setText("导入");
			jButton2.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					JFileChooser chooser = new JFileChooser();
					chooser.setFileFilter(new FileFilter() {

						@Override
						public boolean accept(File f) {
							return f.isDirectory();
						}

						@Override
						public String getDescription() {
							return "directory";
						}

					});
					chooser.setCurrentDirectory(new File("."));
					chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					int retVal = chooser.showOpenDialog(CapturePanel.this);
					if (retVal == JFileChooser.APPROVE_OPTION) {
						File dir = chooser.getSelectedFile();
						File[] fs = dir.listFiles();
						Arrays.sort(fs);
						captureTableModel.clearAll();
						for (File f : fs) {
							String name = f.getName();
							int index = name.lastIndexOf(".");
							if (index == -1) {
								continue;
							}
							String code = name.substring(0, index);
							try {
								BufferedImage image = ImageIO.read(f);
								if (image == null) {
									continue;
								}
								captureTableModel.addColumn(image, code);
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}

					}

				}
			});
		}
		return jButton2;
	}

	public static void main(String[] args) {
		CapturePanel capturePanel = new CapturePanel();
		PanelLauncher launcher = new PanelLauncher(capturePanel);
		launcher.show(400, 300);
	}

	public void found(BufferedImage image) {
		captureTableModel.addImage(image);
	}

}
